package com.shigu.agent.processes;

import com.opentae.data.mall.examples.MoUserAccountExample;
import com.opentae.data.mall.interfaces.*;
import com.shigu.agent.bo.AgentBO;
import com.shigu.agent.enums.UserRoleType;
import com.shigu.agent.exceptions.AgentException;
import com.shigu.agent.model.MoAgent;
import com.shigu.agent.model.impl.MoAgentImpl;
import com.shigu.main4.tools.SpringBeanFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;


/**
 * 代理的服务
 */
@Service
public class AgentProcessImpl implements AgentProcess{

    private static final Logger logger = LoggerFactory.getLogger(AgentProcessImpl.class);


    @Autowired
    ManagerUserRoleMapper managerUserRoleMapper;

    @Autowired
    MoUserAccountMapper moUserAccountMapper;

    @Autowired
    ManagerUserMapper managerUserMapper;

    @Value("${me.operator_id}")
    public Long defaultAgentId;//默认的代理ID
    /**
     * 创建代理
     * @param oemTag oem
     * @param fromId 运营商ID
     * @return
     */
    @Override
    public Long createAgentman(String oemTag, AgentBO agentBO, Long fromId) {
        //如果已经创建了易宝账户，并已经有商户，但没有代理账户就创建一笔代理，加一个代理权限
        return null;
    }

    @Override
    public synchronized void increaseProfile(Long agentId, Double money) throws AgentException {
            if (money==0) {
                return;
            }
            if (0>money) {
                throw new AgentException(money+" 必须为正");
            }
        changeProfit(agentId,money);
    }

    @Override
    public synchronized void reduceProfile(Long agentId, Double money) throws AgentException {
            if (money==0) {
                return;
            }
            if (0>money) {
                throw new AgentException(money+" 必须为正");
            }
            changeProfit(agentId,0-money);
    }

    private synchronized void changeProfit(Long agentId,Double money) throws AgentException {
        MoUserAccountExample example=new MoUserAccountExample();
        example.createCriteria().andUserIdEqualTo(agentId);
        example.setStartIndex(0);
        example.setEndIndex(1);
        if (Double.valueOf(moUserAccountMapper.selectByConditionList(example).get(0).getProfitLeft())+money<0) {
            throw new AgentException("余额不足");
        }
        MoAgent agent= SpringBeanFactory.getBean(MoAgent.class,agentId);
        agent.addProfit(money);
    }


}
